package com.fanrui.code.chess.mahjong;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

import com.fanrui.code.main.MainServer;
import com.fanrui.code.util.FileUtil;
import com.fanrui.code.util.logger.Stdout;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.annotations.Expose;

/**
 * @ClassName: MahjongStandings
 * @Description:麻将战绩
 * @author bear
 */
public class MahjongStandings {
	/**
	 * 麻将玩家
	 */
	@Expose
	private Collection<JsonElement> players;
	@Expose
	private List<StandingsRound> rounds;
	@Expose
	private String id;
	@Expose
	private Collection<Mahjong> heapCards;
	public MahjongStandings(int tableId, Collection<MahjongGamer> players,Collection<Mahjong> heapCards) {
		id = System.currentTimeMillis() + "_" + tableId;
		this.players = new ArrayList<JsonElement>();
		if(players != null){
			for(MahjongGamer gamer : players){
				this.players.add(gamer.toJson());
			}
		}
		this.heapCards = heapCards;
		
	}


	public List<StandingsRound> getRounds() {
		return rounds;
	}

	public void setRounds(List<StandingsRound> rounds) {
		this.rounds = rounds;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String toJson() {
		Gson gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().create();
		try {
			return new String(gson.toJson(this).getBytes(), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return "";
	}
	
	
	
	public void addStandingsRound(StandingsRound round){
		if(round == null){
			return;
		}
		if(rounds == null){
			rounds = new LinkedList<StandingsRound>();
		}
		rounds.add(round);
	}
	
	

	private static BlockingQueue<MahjongStandings> save = new LinkedBlockingQueue<MahjongStandings>();

	public static void startSaveStandings() {
		new Thread(new Runnable() {
			@Override
			public void run() {
				while (true) {
					try {
						MahjongStandings ms = save.take();
						FileUtil.writeFile(MainServer.getInstance().standURL+ms.getId()+".json", ms.toJson());
						Stdout.GET().info("--------Save Standings: "+ms.getId());
					} catch (InterruptedException e) {
						e.printStackTrace();
					}

				}
			}
		}).start();
	}

	public static void addStandings(MahjongStandings ms) {
		try {
			save.put(ms);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}

	}
	


	public enum StandingsOperationType{
		Huan,
		Que,
		Touch,
		Send,
		Hu,
		Peng,
		Gang,
		Chi,
		ZiMo;
	}
}
